package org.learn;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: qingle
 * @Date: 2024/9/8-23:50
 * @Description: 线程池的关闭
 * @version: 1.0
 */
public class PoolTest03 {

	public static void main(String[] args) throws InterruptedException {
		ThreadPoolExecutor threadPoolExecutor = null;

		try {
			// 创建线程池对象
			threadPoolExecutor = new ThreadPoolExecutor(2, 3, 1, TimeUnit.SECONDS,
	     new ArrayBlockingQueue<>(2)
			);

			// 创建任务
			Runnable r = () -> {
				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("线程池中的线程：" + Thread.currentThread().getName());
			};

			// 将任务交给线程池
			for (int i = 0; i < 5; i++) {
				threadPoolExecutor.execute(r);
			}
		} finally {
			// 关闭线程池
			if(threadPoolExecutor != null) {
				threadPoolExecutor.shutdown(); // 队列中的任务耗时非常长
				// 等待1秒, 如果还没有完成，则强制关闭
				if (!threadPoolExecutor.awaitTermination(10, TimeUnit.SECONDS)) {
					threadPoolExecutor.shutdownNow();
				}
			}
		}

//		System.out.println(threadPoolExecutor);
//
//		TimeUnit.SECONDS.sleep(10);
//		System.out.println(threadPoolExecutor);
//		// 关闭线程池
//		threadPoolExecutor.shutdown();
//		try {
//			if (!threadPoolExecutor.awaitTermination(1, TimeUnit.MINUTES)) {
//				threadPoolExecutor.shutdownNow(); // 如果超时未完成，则强制关闭
//			}
//		} catch (InterruptedException e) {
//			threadPoolExecutor.shutdownNow(); // 中断时强制关闭
//		}
	}
}
